package com.lg.order.producer.config;

import com.lg.order.producer.entity.MessageEntity;
import com.lg.order.producer.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @author by Mr. Li 2020/12/11 10:09
 */
@Configuration
@Slf4j
public class MyRabbitMqGlobalConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MessageService mqMessageService;

    /**
     * 确保消息的可靠性，将失败的信息记录到数据库，定时任务重发
     * 1. 服务受到消息就回调
     * spring.rabbitmq.publisher-confirm-type: simple
     * 2. 设置确认回调 confirmCallback
     * spring.rabbitmq.publisher-returns=true
     * spring.rabbitmq.tempLate.mandatory=true
     *
     * @PostConstruct,在MyRabbitMqConfig对象创建完成后执行这个方法
     */
    @PostConstruct
    public void initRabbitTemplate() {
        // 1. 设置服务受到消息就回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 服务器收到消息就回调
             * @param correlationData 当前消息的唯一关联数据（包含消息唯一id)
             * @param ack 消息是否成功收到
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                log.info("RabbitMQ是否成功收到消息：{}", ack);
                if (ack && correlationData != null) {
                    try {
                        //  服务器收到消息，将该消息的状态保存进数据库
                        MessageEntity mqMessage = new MessageEntity();
                        mqMessage.setCreateTime(new Date());
                        mqMessage.setMessageStatus(0);
                        mqMessage.setMessageId(correlationData.getId());
                        mqMessageService.save(mqMessage);
                    } catch (Exception e) {
                        log.error("该消息已经存在，messageId为：{}", correlationData.getId());
                    }
                }
            }
        });

        // 2. 消息没有到达指定的队列回调
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            /**
             *
             *消息没有到达指定的队列触发，这个回调如果被触发会比confirm回调先触发
             *@param returnedMessage message    投递失败的消息信息
             *                         replyCode  回复码
             *                         replyText  回复的文本内容
             *                         exchange   当时消息发给哪个交换机
             *                         routingKey 当时消息发给哪个交换机时的路由键
             *           在spring boot 2.4 上述内容被整合成了 returnedMessage
             */
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                Message message = returnedMessage.getMessage();
                log.info("消息没有正确到达指定的队列回调：{}", message.getBody());
                // 消息id
                String messageId = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
                // 消息类型
                String messageType = (String) message.getMessageProperties().getHeaders().get("__TypeId__");
                // 消息内容
                String messageContent = new String(message.getBody());
                // 更新消息状态，后面启用定时任务重新发送
                MessageEntity mqMessage = new MessageEntity();
                mqMessage.setMessageStatus(1);
                mqMessage.setUpdateTime(new Date());
                mqMessage.setMessageId(messageId);
                mqMessage.setClassType(messageType);
                mqMessage.setToExchane(MyMQConfig.DISTRIBUTED_TRANSACTION_EVENT_EXCHANGE);
                mqMessage.setRoutingKey(MyMQConfig.DISTRIBUTED_TRANSACTION_KEY);
                mqMessage.setContent(messageContent);
                mqMessageService.updateById(mqMessage);
            }
        });
    }
    /**
     * 将rabbit序列化 转换成json
     * 默认是java的序列化
     *
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
